import { watch } from 'vue'
import { useThemeStore } from '@/store/modules/theme'
import { storeToRefs } from 'pinia'
import { THEME } from '@/constants/theme'

/**
 * 监听系统主题变化
 */
let matchMedia
const watchSystemThemeChange = () => {
  if (matchMedia) return
  matchMedia = window.matchMedia('(prefers-color-scheme: dark)')
  matchMedia.addEventListener('change', () => {
    watchThemeChange(THEME.SYSTEM)
  })
}

/**
 * 监听主题变化
 * @param {*} theme 主题类型
 * @returns
 */
const watchThemeChange = (theme) => {
  let themeClassName = ''
  switch (theme) {
    case THEME.LIGHT:
      themeClassName = 'light'
      break
    case THEME.DARK:
      themeClassName = 'dark'
      break
    case THEME.SYSTEM:
      watchSystemThemeChange()
      themeClassName = matchMedia?.matches ? 'dark' : 'light'
  }
  document.querySelector('html').className = themeClassName
}

export default () => {
  const themeStore = useThemeStore()
  const { themeType } = storeToRefs(themeStore)
  watch(themeType, watchThemeChange, { immediate: true })
}
